package com.ethan.crm.service.impl;

import com.ethan.crm.domain.Employee;
import com.ethan.crm.domain.Role;
import com.ethan.crm.mapper.EmployeeMapper;
import com.ethan.crm.page.PageResult;
import com.ethan.crm.query.EmployeeQueryObject;
import com.ethan.crm.service.IEmployeeService;
import com.ethan.crm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeDao;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return employeeDao.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insert(Employee record) {
        AjaxResult result;
        try {
            record.setPassword("88888888");
            record.setAdmin(false);
            record.setState(true);
            employeeDao.insert(record);
            //增加员工对应角色信息
            List<Role> roles = record.getRoles();
            for (Role role : roles) {
                employeeDao.insertEmpAndRoleRelation(role.getId(),record.getId());
            }
            result = new AjaxResult(true,"新增员工成功！");
        } catch (Exception e) {
            //用于事务回滚的
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result = new AjaxResult("新增员工失败，请联系管理员！");
        }
        return result;
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeDao.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Employee record) {
        int effectCount = employeeDao.updateByPrimaryKey(record);
        //删除员工之前的角色信息
        employeeDao.deleteRolesOfEmpByEid(record.getId());
        //新增员工的角色信息
        List<Role> roles = record.getRoles();
        for (Role role : roles) {
            employeeDao.insertEmpAndRoleRelation(role.getId(),record.getId());
        }
        return effectCount;
    }

    @Override
    public int updateState(Long id) {
        return employeeDao.updateState(id);
    }

    @Override
    public Employee getEmployeeForLogin(String username, String password) {
        return employeeDao.getEmployeeForLogin(username,password);
    }

    @Override
    public PageResult queryForPage(EmployeeQueryObject qo) {
        Long total = employeeDao.queryForPageCount(qo);
        if (total == 0){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Employee> employeeList = employeeDao.queryForPage(qo);
        return new PageResult(total.intValue(), employeeList);
    }
}
